﻿using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Read.Api.Application.Commands;
using B.S.Database.Read.Api.Dtos.RequsetDtos;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace B.S.Database.Read.Api.Application.CommandHandler
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommands, Apiresult<UserDtos>>
    {
        private readonly IBaseResotity<User> userReposity;
        private readonly IBaseResotity<Role> roleResotity;
        private readonly IBaseResotity<UserRole> userRoleResotity;

        public UserLoginCommandHandler(IBaseResotity<User> UserReposity,IBaseResotity<Role> RoleResotity,IBaseResotity<UserRole> UserRoleResotity)
        {
            userReposity = UserReposity;
            roleResotity = RoleResotity;
            userRoleResotity = UserRoleResotity;
        }
        public Task<Apiresult<UserDtos>> Handle(UserLoginCommands request, CancellationToken cancellationToken)
        {
            Apiresult<UserDtos> res = new Apiresult<UserDtos>();
            res.Code = ApiEnums.成功;
            res.Message = ApiEnums.成功.ToString();
            var list = from a in userReposity.GetAll().ToList()
                       join b in userRoleResotity.GetAll().ToList() on a.UserId equals b.UserId
                       join c in roleResotity.GetAll().ToList() on b.RoleId equals c.RoleId
                       where a.UserPass == request.UserPass.GetMD5() && a.UserName == request.UserName
                       select new UserDtos
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserNickName = a.UserNickName,
                           UserPass = a.UserPass,
                           RoleId = c.RoleId,
                           RoleName = c.RoleName,
                           Token = CreateTokenString()
                       };
            if(list.Count()==0)
            {
                res.Code = ApiEnums.失败;
                res.Message = ApiEnums.失败.ToString();
            }
            res.Data = list.FirstOrDefault();
            return Task.FromResult(res);
            //1221111
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
